package influx

import (
	"errors"
	"fmt"
	"github.com/influxdata/influxdb/client/v2"
	"net/url"
	"time"
)

var (
	ErrGetPasswordFailed = errors.New("get password failed")
)

func NewClient(host, user, passwd string) (client.Client, error) {
	opt, err := url.Parse("influx://" + user + ":" + passwd + "@" + host)
	if err != nil {
		return nil, err
	}

	password, ok := opt.User.Password()
	if !ok {
		return nil, ErrGetPasswordFailed
	}

	// 连接
	httpClient, err := client.NewHTTPClient(client.HTTPConfig{
		Addr:     fmt.Sprintf("http://%s", opt.Host),
		Username: opt.User.Username(),
		Password: password,
		Timeout:  time.Second * 5,
	})

	if err != nil {
		return nil, err
	}

	return httpClient, nil
}
